package com.tycom.simpleapp.jaxb;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import com.tycom.simpleapp.jaxb.Response.Row;
import com.tycom.simpleapp.model.Company;
import com.tycom.simpleapp.services.CompanyService;

@Component
@DependsOn (value = "transactionManager")
public class CompanyXml {
	
	Logger logger = LoggerFactory.getLogger(CompanyXml.class);
    
	@Autowired
	CompanyService companyService;
	
	@PostConstruct
	public void processData() {
		try {

			JAXBContext jaxbContext = JAXBContext.newInstance(CompanyXml.class
					.getPackage().getName());
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			
			Response cfg = (Response) unmarshaller.unmarshal(getClass().getResourceAsStream("company.xml"));
			List<Company> list = new ArrayList<Company>();
			System.out.println("Starting insert of the records...");
			long t1 = System.currentTimeMillis();
			for (Row row : cfg.getRow()) {
				list.add(convertCompanyData(row));
			}
			companyService.saveAll(list);
			
			System.out.println("Time taken for inserting the records:" + (System.currentTimeMillis() - t1));
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}
	
	public Company convertCompanyData(Row row) {
		Company company = new Company();
		company.setCity(row.getCity());
		company.setGrowth(row.getGrowth());
		company.setIndustry(row.getIndustry());
		company.setName(row.getCompany().getDescription());
		company.setPosition(row.getPosition().intValueExact());
		company.setRank(row.getRank().intValueExact());
		company.setRevenue(row.getRevenue());
		company.setState(row.getState());
		company.setUrl(row.getCompany().getUrl());
		return company;
	}
}
